// Copyright (c) 2012 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "net/http/server/event/handler.h"

#include <re2/re2.h>

#include <vector>

#include "net/http/server/event/event_server.h"
#include "net/http/server/event/request.h"

namespace sg {
namespace net {
namespace http {
namespace server {
namespace event {

Handler::Handler(Callback cb, void *arg)
    : cb_(cb), arg_(arg), uri_regex_(),
      protocol_hosts_(NULL), not_protocol_host_(),
      not_protocol_encrypted_(false) {
}

bool Handler::Run(Request *request) {
  if (!not_protocol_host_.empty()) {
    std::string host;
    request->GetHeader("Host", &host);

    // for local server, drop the port
    size_t colon_index = host.find(":");
    if (colon_index != std::string::npos) {
      host = host.substr(0, colon_index);
    }

    if (not_protocol_host_ == host &&
        not_protocol_encrypted_ == request->IsEncrypted()) {
      return false;
    }
  }

  if (!uri_regex_.empty() &&
      !RE2::FullMatch(request->request_path(), uri_regex_)) {
    return false;
  }

  cb_(request, arg_);
  return true;
}

void Handler::set_uri_regex(const std::string &uri_regex,
                            std::vector<ProtocolHost> *allowed_hosts) {
  uri_regex_ = uri_regex;
  protocol_hosts_ = allowed_hosts;
}

void Handler::set_not_protocol_host(const std::string &host,
                                    const bool encrypted) {
  not_protocol_host_ = host;
  not_protocol_encrypted_ = encrypted;
}


}  // namespace event
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg
